package com.coda.service.impl;

import com.coda.constant.MessageConstant;
import com.coda.constant.StatusConstant;
import com.coda.context.BaseContext;
import com.coda.exception.BaseException;
import com.coda.mapper.UserMapper;
import com.coda.pojo.User;
import com.coda.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @return
     */
    @Override
    public User login(User user) {
        //获取用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        //用户信息
        User userInfo = null;

        //判断是邮箱登录还是用户名登录
        String loginType = user.getLoginType();
        if (StatusConstant.LOGIN_BY_USERNAME.equals(loginType)){
            log.info("用户名登录："+username);
            //用户名登录
            if (username == null ) {
                throw new BaseException(MessageConstant.NAME_IS_EMPTY);
            }
            userInfo = userMapper.getUserByName(username);
        }else if (StatusConstant.LOGIN_BY_EMAIL.equals(loginType)){
            log.info("邮箱登录："+email);
            //邮箱登录
            if (email == null){
                throw new BaseException(MessageConstant.EMAIL_IS_NULL);
            }
            //判断邮箱格式
            if (!(email.matches("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"))) {
                throw new BaseException(MessageConstant.EMAIL_IS_ILLEGAL);
            }
            userInfo = userMapper.getUserByEmail(email);
        }else {
            throw new BaseException(MessageConstant.LOGIN_TYPE_ERR);
        }

        //判断密码是否为空
        if (password == null) {
            throw new BaseException(MessageConstant.PASSWORD_IS_EMPTY);
        }

        //判断用户是否存在
        if (userInfo == null) {
            throw new BaseException(MessageConstant.USERNAME_OR_PASSWORD_ERR);
        }

        //根据md5加密和数据库匹配
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!(password.equals(userInfo.getPassword()))){
            throw new BaseException(MessageConstant.USERNAME_OR_PASSWORD_ERR);
        }

        //判断用户状态是否为禁用
        if (StatusConstant.userStatusForbid.equals(userInfo.getStatus())){
            throw new BaseException(MessageConstant.FORBID);
        }
        //更新用户登录时间
        User userUpdate = new User();
        userUpdate.setId(userInfo.getId());
        userUpdate.setLastLogin(LocalDateTime.now());
        userMapper.update(userUpdate);
            return userInfo;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public int register(User user) {
        //判断表单信息
        //昵称是否为空
        if (user.getNickname() == null) {
            throw new BaseException(MessageConstant.NICK_IS_NULL);
        }
        //邮箱是否为空
        if (user.getEmail() == null){
            throw new BaseException(MessageConstant.EMAIL_IS_NULL);
        }
        //密码是否为空
        if (user.getPassword() == null) {
            throw new BaseException(MessageConstant.PASSWORD_IS_EMPTY);
        }
        //判断邮箱名合法性
        if (!(user.getEmail().matches("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"))) {
            throw new BaseException(MessageConstant.EMAIL_IS_ILLEGAL);
        }
        //判断该邮箱是否已经被注册过
        User userInfo = userMapper.getUserByEmail(user.getEmail());
        if (userInfo != null){
            throw new BaseException(MessageConstant.EMAIL_IS_EXISTS);
        }
        //生成用户名
        String account;
        Random random = new Random();
        do {
             account = String.format("%09d", random.nextInt(1_000_000_000));
        }while (userMapper.getUserByName(account) != null);

        //设置基本信息
        //设置用户名
        user.setUsername(account);
        user.setLongestStreak(0);
        user.setStatus(StatusConstant.userStatusEnable);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        //将密码加密
        String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Password);

        return userMapper.addUser(user);
    }
}
